import 'package:flutter/material.dart';
import 'package:flutter_yishop/constants/Constants.dart';
import '../../utils/screen/ScreenAdapter.dart';
import '../../model/CategoryModel.dart';
import 'package:dio/dio.dart';
import '../../config/Config.dart';

class Category extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _Category();
  }
}

class _Category extends State<Category> with AutomaticKeepAliveClientMixin {
  int _selectedIndex = 0;
  var _leftCategoryData = [];
  var _rightCategoryData = [];

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  void initState() {
    _getLeftCategoryData();
    print("cate");
  }

  //左侧分类
  _getLeftCategoryData() async {
    var api = "${Config.url}api/pcate";
    var result = await Dio().get(api);
    var leftList = CategoryModel.fromJson(result.data);
    setState(() {
      this._leftCategoryData = leftList.result;
    });
    var ss = _leftCategoryData[0].id;
    print(ss);
    _getRightCategoryData(_leftCategoryData[0].id);
  }

  //右侧分类
  _getRightCategoryData(pid) async {
    var api = "${Config.url}api/pcate?pid=${pid}";
    var result = await Dio().get(api);
    var rightList = CategoryModel.fromJson(result.data);
    setState(() {
      this._rightCategoryData = rightList.result;
    });
  }

  Widget _leftCategoryWidget(value, leftWidth) {
    if (value.length > 0) {
      return Container(
        width: leftWidth,
        height: double.infinity,
        child: ListView.builder(
            itemCount: value.length,
            itemBuilder: (context, index) {
              return Column(
                children: <Widget>[
                  InkWell(
                    onTap: () {
                      setState(() {
                        _selectedIndex = index;
                        _getRightCategoryData(value[index].id);
                      });
                    },
                    child: Container(
                      width: double.infinity,
                      child: Padding(
                        padding: EdgeInsets.all(15),
                        child: Text(
                          "${value[index].title}",
                          style: TextStyle(),
                          textAlign: TextAlign.center,
                        ),
                      ),
                      color: _selectedIndex == index
                          ? Color.fromRGBO(240, 246, 246, 0.9)
                          : Colors.white,
                    ),
                  ),
                  Divider(
                    height: 0,
                  )
                ],
              );
            }),
      );
    } else {
      return Container(width: leftWidth, height: double.infinity);
    }
  }

  Widget _rightCategoryWidget(value, rightItemWidth, rightItemHeight) {
    if (value.length > 0) {
      return Expanded(
          flex: 1,
          child: Container(
            padding: EdgeInsets.all(10),
            height: double.infinity,
            color: Color.fromRGBO(240, 246, 246, 0.9),
            child: GridView.builder(
              itemCount: value.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  childAspectRatio: rightItemWidth / rightItemHeight,
                  mainAxisSpacing: ScreenAdapter.height(10),
                  crossAxisSpacing: ScreenAdapter.height(10)),
              itemBuilder: (context, index) {
                //图片
                String sPic = value[index].pic;
                sPic = Config.url + sPic.replaceAll('\\', '/');
                return InkWell(
                  onTap: (){
                    print(value[index].id);
                    Navigator.pushNamed(context, Constants.PRODUCT,arguments:{
                      "cid":value[index].id,"title":value[index].title
                    });
                    // Navigator.pushNamed(context, Constants.PRODUCT,arguments:{
                    //   "cid":value[index].id
                    // });
                  },
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        AspectRatio(
                          aspectRatio: 1 / 1,
                          child: Image.network(
                            "${sPic}",
                            fit: BoxFit.cover,
                          ),
                        ),
                        Container(
                          child: Text(value[index].title),
                        )
                      ],
                    ),
                  ),
                );
              },
            ),
          ));
    } else {
      return Expanded(
          flex: 1,
          child: Container(
            padding: EdgeInsets.all(10),
            height: double.infinity,
            color: Color.fromRGBO(240, 246, 246, 0.9),
            child: Text("加载中..."),
          ));
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    //这句是AutomaticKeepAliveClientMixin最容易忽略的，重要，必写
    super.build(context);
    ScreenAdapter.init(context);

    //计算右侧GridView宽高比
    var leftWidth = ScreenAdapter.getScreenWith() / 4;
    //右侧每一项宽度=（总宽度-左侧宽度-GridView外侧元素左右的Padding值-GridView中间的间距）/3
    var rightItemWidth =
        (ScreenAdapter.getScreenWith() - leftWidth - 20 - 20) / 3;

    //获取计算后的宽度
    rightItemWidth = ScreenAdapter.width(rightItemWidth);

    //获取计算后的高度
    var rightItemHeight = rightItemWidth + ScreenAdapter.height(28);

    return Row(
      children: <Widget>[
        _leftCategoryWidget(this._leftCategoryData, leftWidth),
        _rightCategoryWidget(
            this._rightCategoryData, rightItemWidth, rightItemHeight)
      ],
    );
  }


}
